package main.controller.admin;

import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import main.RequestHelper;
import main.TimeHelper;
import main.database.AccountHelper;
import main.GlobalConfig;
import main.database.DatabaseMan;
import org.bson.Document;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Controller
public class FictionAddPageController {
    @GetMapping("/fictionadd")
    public String fictionAddPage(ModelMap modelMap, HttpServletRequest request) {
        boolean isAdmin = false;

        String uuid = RequestHelper.getUserUUIDFromRequest(request);
        isAdmin = AccountHelper.isAdminFromUUID(uuid);
        String account = AccountHelper.getAccountInfoFromUUID(uuid);

        if (isAdmin) {
            List<String> catlogList = new ArrayList<>();

            MongoCollection<Document> collection = DatabaseMan.Instance().GetCollection(GlobalConfig.collectionNameOfRootCatlog);
            FindIterable<Document> documents = collection.find();
            for (Document doc : documents) {
                if (doc.containsKey("name")) {
                    catlogList.add((String) doc.get("name"));
                }
            }

            modelMap.put("catloglist", catlogList);
            modelMap.put("userName", account);
            modelMap.put("year2year", TimeHelper.getFormattedYear2Year());

            return "/admin/fictionAddPage";
        }
        else {
            return "/admin";
        }
    }
}